from rest_framework.response import Response
from rest_framework.views import APIView
from apps.absent.models import Absent
from apps.absent.serializers import AbsentSerializer
from apps.inform.models import Inform, InformRead
from apps.inform.serializers import InformSerializer
from django.db.models import Q, Prefetch, Count
from apps.oaauth.models import OADepartment
from django.views.decorators.cache import cache_page
from django.utils.decorators import method_decorator
@cache_page(60 * 15)
def test_cache_demo(request):
    pass

class LatestInfoView(APIView):
    """
        返回最新的十条通知
        返回公共的，或者是自己所在的部门所能看到的
    """
    @method_decorator(cache_page(60 * 15))
    def get(self, request):
        current_user = request.user
        informs = Inform.objects.prefetch_related(Prefetch(
            'reads', queryset=InformRead.objects.filter(user_id=current_user.uid)
        ), "departments").filter(Q(public=True) | Q(departments=current_user.department))[:10]
        serializer = InformSerializer(informs, many=True)
        return Response(serializer.data)

class LatestAbsentView(APIView):
    """
            返回最新的十条考勤信息
            董事会可以看到所有，非董事会可以看到当前部门的考勤信息
        """
    @method_decorator(cache_page(60 * 15))
    def get(self, request):
        current_user = request.user
        queryset = Absent.objects
        if current_user.department.name != "董事会":
            queryset = Absent.objects.filter(requester__department_id=current_user.department.id)
        queryset = queryset.all()[:10]
        serializer = AbsentSerializer(queryset, many=True)
        return Response(serializer.data)

class DepartmentView(APIView):
    """
            返回部门员工数量
        """
    @method_decorator(cache_page(60 * 15))
    def get(self, request):
        rows = OADepartment.objects.annotate(staff_count=Count('staffs')).values("staff_count", "name")
        return Response(rows)


class HealthCheckView(APIView):
    def get(self, request):
        return Response({"code": 200})
